import argparse
import requests
import logging
import time

class ArmClient:
    def __init__(self, ip: str = "192.168.0.113", port: int = 5000):
        """
        初始化 HTTP 客户端
        """
        self.server_url = f"http://{ip}:{port}"
        self.headers = {'Content-Type': 'application/json'}

    def send(self, command: str) -> dict:
        """
        发送命令给 HTTP 服务器，获取命令执行结果 ID

        :param command: 要发送给服务器的命令
        :return: 返回服务器返回的命令 ID
        """
        url = f"{self.server_url}/arm"
        payload = {"command": command}
        try:
            response = requests.post(url, json=payload, headers=self.headers)
            result = response.json()
            return result
        except requests.exceptions.RequestException as e:
            logging.error(f"Error sending command: {e}")
            return {"code": 1, "message": f"Error sending command: {e}"}

    def recv(self, command_id: str, timeout: int = 10) -> str:
        """
        查询指定命令 ID 的执行结果

        :param command_id: 要查询的命令 ID
        :param timeout: 超时时间，默认 10 秒
        :return: 返回命令的执行结果消息
        """
        url = f"{self.server_url}/arm"
        params = {"id": command_id}

        end_time = time.time() + timeout

        while time.time() < end_time:
            try:
                response = requests.get(url, params=params, headers=self.headers, timeout=timeout)
                result = response.json()
                if result.get("code") == 0:
                  return result

                logging.warning(f"Command {command_id} failed, message: {result['message']}")
            except Exception as e:
                logging.error(f"Error querying command {command_id}: {e}")
                return {"code": 1, "message": f"Error querying command {command_id}: {e}"}

            time.sleep(1)  # 每秒重试一次，避免过于频繁的请求

        logging.error(f"querying command {command_id} timeout")
        return {"code": 2, "message": f"querying command {command_id} timeout"}

def main() -> None:
    """
    Main entry point for the program. Parses command-line arguments and starts the HTTP server
    and Websocket client in separate threads.
    """
    logging.basicConfig(level=logging.INFO)

    parser = argparse.ArgumentParser(description="Control robotic arm via HTTP and WebSocket.")
    parser.add_argument("--ip", type=str, default="192.168.0.113", help="HTTP server IP address")
    parser.add_argument("--port", type=int, default=5000, help="HTTP server port")

    args = parser.parse_args()

    client = ArmClient(args.ip, args.port)

    command = "不如跳舞"
    result = client.send(command)
    if result["code"] != 0:
        print(f'发送命令"{command}"给机械臂失败：{result["message"]}')
        return

    print(f'发送命令"{command}"给机械臂成功')
    command_id = result["id"]
    result = client.recv(command_id, timeout=10)
    if result["code"] != 0:
        print(f'从机械臂接收命令"{command}"的执行结果失败：{result["message"]}')
        return

    print(f'机械臂执行命令"{command}"成功')

if __name__ == "__main__":
    main()
